package com.resoft.bigdata.p2p.job;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.resoft.bigdata.p2p.record.DebtorInfo;
import com.resoft.bigdata.p2p.record.InvestInfo;
import com.resoft.bigdata.p2p.record.LoanContract;
import com.resoft.bigdata.p2p.record.MonthlyStatistics;
import com.resoft.bigdata.p2p.service.api.QueryService;
import com.resoft.bigdata.p2p.service.api.thrift2imp.Thrift2QueryServiceImpl;

public class DailyReportStatistic  {
	QueryService qry = null;
	
	public DailyReportStatistic(String host, int port){
		qry =  new Thrift2QueryServiceImpl(host, port);
	}
	
	public List<MonthlyStatistics> getMonthlyStatistics(List<String> orgCodes, String beginDate, String endDate) throws IOException{
		List<MonthlyStatistics> mss = new ArrayList<MonthlyStatistics>();
		for(String orgCode: orgCodes){
			mss.add(getMonthlyStatistics(orgCode, beginDate, endDate));
		}
		
		return mss;
	}
	
	public MonthlyStatistics getMonthlyStatistics(String orgCode, String beginDate, String endDate) {
		MonthlyStatistics ms = new MonthlyStatistics();
		
		boolean first = true;
		
		byte [] lastRow = null;
		int loop = 0;
		while(true){
			++loop;
			List<LoanContract> contracts = null;
			try {
				contracts = qry.getLoanContractByOrgCodeAndDates(orgCode, beginDate, endDate, 1000, lastRow );
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			if(contracts == null || contracts.isEmpty()){
				System.out.println(" Loan loop:" + loop + ", p2p orgcode:" + orgCode);
				break;
			}
			
			for(LoanContract contract : contracts){
				//System.out.println(contract);
				if(first){
					ms.setOrgCode(contract.getOrgCode());
					ms.setP2pOrgCode(contract.getOrgCode());
					ms.setOrgName(contract.getOrgName());
					ms.setP2pOrgName(contract.getOrgName());
					ms.setBankId(contract.getBankId());
					
					first = false;
				}
				//1借款标数
				ms.addTotalCreditNumber(1);
				//2项目金额
				float xmje = Float.parseFloat(contract.getXmje());
				ms.addCreditBalancer(xmje);

				//3借款利率
				float jklv; 
				if(contract.getJklv().contains("%")){
					jklv = Float.parseFloat(contract.getJklv().replace("%", ""))/100;
				}else{
					jklv =  Float.parseFloat(contract.getJklv());
				}
				
				ms.addTmpTotalInterest(jklv*xmje);
				
				//借款项目期限
				int xmqx = Integer.parseInt(contract.getXmqx());
				//借款期限类型
				String qxlx = contract.getQxlx();
				float scale = 1;
				switch(qxlx){
				case "天":
					scale = (float)1.0/30;
					break;
				case "季度":
				case "季":
					scale = 3;
					break;
				case "年":
					scale = 12;
				case "月":
					scale = 1;
				}
				//总借款期限
				ms.addTmpTotalPerloanPeriod(scale*xmqx);
			}
			lastRow = contracts.get(contracts.size()-1).getStoredRowKey();

		} // ~~while
		
		ms.setPerLoanPeriod(ms.getTmpTotalPerLoanPeriod()/ms.getTotalCreditNumber());
		//3借款利率水平
		ms.setInterestRate(ms.getTmpTotalInterest()/ms.getCreditBalancer());
		
		// query debtor info
		lastRow = null;
		loop = 0;
		while(true){
			++loop;
			List<DebtorInfo> debtors = qry.getDebtorInfoByOrgCodeAndDates(orgCode, beginDate, endDate, 1000, lastRow );
			if(debtors == null || debtors.isEmpty()){
				System.out.println("Debtor loop:" + loop + ", p2p orgcode:" + orgCode);
				break;
			}
			
			for(DebtorInfo debtor : debtors){
				//System.out.println(debtor);
				//1、贷款借款人数（人）----DebtorInfo.jkr
				ms.addDebtors(1);
				//2、待还余额（万元）----DebtorInfo.zptyqzjr TODO: 这样做不对，应该考虑借款日期和还款方式，还有逾期情况
				float xmje = Float.parseFloat(debtor.getZptyqzjr() !=null ? debtor.getZptyqzjr() : "0");
				ms.addCreditBalancer(xmje);
			}
			lastRow = debtors.get(debtors.size()-1).getStoredRowKey();

		} // ~~while
		ms.setPerCreditBalance(ms.getCreditBalancer()/ms.getDebtors());

		// query investor info
		lastRow = null;
		loop = 0;
		while(true){
			++loop;
			List<InvestInfo> investors = qry.getInvestInfoByOrgCodeAndDates(orgCode, beginDate, endDate, 1000, lastRow );
			if(investors == null || investors.isEmpty()){
				System.out.println("invest loop:" + loop + ", p2p orgcode:" + orgCode);
				break;
			}
			
			for(InvestInfo investor : investors){
				//System.out.println(investor);
				//1、贷款借款人数（人）----DebtorInfo.jkr
				ms.addInvestors(1);
				//2、资金净流入（万元）--- InvestInfo.tzje TODO: 这样做不对，应该考虑借款日期和还款方式，还有逾期情况
				float xmje = Float.parseFloat(investor.getTzje() != null ? investor.getTzje() : "0");
				ms.addTmpTotaltzje(xmje);
			}
			lastRow = investors.get(investors.size()-1).getStoredRowKey();

		} // ~~while
		ms.setPerCreditBalance(ms.getCreditBalancer()/ms.getDebtors());
		ms.setNetInflows(ms.getTmpTotaltzje() - ms.getCreditBalancer());
		
		System.out.println(ms.toString());
		return ms;
	}
}
